<template>
    <div class="flower-manage-container">
      <el-card class="header">
        <div class="header-content">
            <div class="search">
                <span>鲜花名搜索</span>
                <el-input v-model="nameSearch" class="input"></el-input>
                <el-button @click="handleSearch" type="primary">搜索</el-button>
            </div>
             <el-button type="primary"  @click="flowerAdd">添加鲜花</el-button>
        </div>
      </el-card>
      <el-card>
        <el-table v-loading="loading" :data="tableData" style="width: 100%" border >
          <!-- 序列号 -->
          <el-table-column label="#" type="index" align="center" />
          <!-- 鲜花名称 -->
          <el-table-column label="鲜花名称" prop="name" align="center"/>
          <!-- 价钱 -->
          <el-table-column label="价钱" prop="price" align="center" />
          <!-- 照片 -->
          <el-table-column label="鲜花样式" align="center">
            <template #default="{ row }">
              <el-image
                class="avatar"
                :src="row.src"
                :preview-src-list="[row.src]"
              />
            </template>
          </el-table-column>
          <!-- 鲜花种类 -->
          <el-table-column label="鲜花种类" prop="type" align="center">
            <template #default="{ row }">
              <el-tag size="mini" :type="row.type == '爱情鲜花' ? 'danger': row.type == '友情鲜花' ? 'success' : row.type == '生日鲜花' ? 'warning' : row.type == '祝贺鲜花' ? '' :''">
                {{ row.type }}</el-tag>
            </template>
          </el-table-column>
          <!-- 库存 -->
          <el-table-column label="鲜花库存" prop="inventory" align="center"/>
          <!-- 销售量 -->
          <el-table-column label="销售量" prop="allSalesVolumes" align="center" />
          <!-- 是否热销 -->
          <el-table-column label="是否热销" prop="hot" align="center">
            <template #default="{ row }">
              <el-tag size="mini" :type="row.hot == true ? 'danger':'warning'">
                {{ row.hot == true ? '热销':'非热销' }}</el-tag>
            </template>
          </el-table-column>
          <!-- 操作 -->
          <el-table-column
            :label="$t('msg.excel.action')"
            fixed="right"
            width="180"
            align="center"
          >
            <template #default="{ row }">
              <el-button type="primary" size="mini" @click="onReviseFlower(row)">{{
                $t('msg.excel.revise')
              }}</el-button>
              <el-button type="danger" size="mini" @click="onDeleteFlower(row)">{{
                $t('msg.excel.remove')
              }}</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          class="pagination"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          :current-page="page"
          :page-sizes="[2, 5, 10, 20]"
          :page-size="size"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </el-card>
    </div>
    <Dialog  
        v-if="dialogVisible" 
        :dialogVisible="dialogVisible" 
        :type="buttonType"
        :flowerFormInitial="flowerFormInitial"
        @dialogShow="dialogShow"
        @Confirm="handleConfirm"
        />
  </template>
  
  <script setup>
  import { onMounted, ref, onActivated,reactive } from 'vue'
  import { watchSwitchLang } from '@/utils/i18n'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import { useI18n } from 'vue-i18n'
  import {flowerSearch,flowerDelete,flowerCreate,flowerModify} from '@/api/flowers'
  import Dialog from './components/Dialog.vue'
  // 存储表格数据
  const tableData = ref([])
  const total = ref(0)
  const page = ref(1)
  const size = ref(5)
  const i18n = useI18n()
//   弹框是否展示
  const dialogVisible = ref(false)
// 弹框的title标题
const dialogTitle = ref('')
// 点击的类型
const buttonType = ref('')
// 名称搜索
const nameSearch = ref('')
let loading = ref(false)
// 弹框value值
const flowerFormInitial = ref()
  // 调用接口,获取表格数据
  const getFlowerInfo = async () =>{
    loading.value = true
    const result = await flowerSearch({
      page: page.value,
      pageSize: size.value
    })
    tableData.value = result.findData
    // total.value = result.total
    loading.value = false
  }
//   点击搜索时的回调函数
const handleSearch = async() =>{
  page.value = 1
     // 调用模糊搜索的接口
  const query = {
    name:nameSearch.value,
    page:page.value,
    pageSize:size.value
  }
  const data = await flowerSearch(query)
  tableData.value = data.findData
  total.value = data.findData.length
  // 修改分页器总数的显示，当输入框中搜索东西的时候，再这样修改
  if(nameSearch.value !== ''){
    total.value = data.findData.length
  }else{
    // 没有输入东西的时候，通过接口获取全部数据，再进行赋值
    const getData = await flowerSearch()
    total.value = getData.findData.length
  }
  nameSearch.value = ''
}
  // page-size改变时触发
  const handleSizeChange = (currentSize) => {
    size.value = currentSize
    getFlowerInfo()
  }
  // current-page 改变时触发
  const handleCurrentChange = (currentPage) => {
    page.value = currentPage
    getFlowerInfo()
  }
// 添加鲜花按钮
const flowerAdd = () =>{
    dialogVisible.value = true
    // dialogTitle.value = '添加鲜花信息'
    buttonType.value = "add"
}
// 弹框关闭时
const dialogShow =(isShow) =>{
    dialogVisible.value = isShow
}
// 子组件点击确定时的回调函数
const handleConfirm = async (value,type) =>{
  loading.value = true
    const flowerInfo = {
        ...value,
        price:Number(value.price),
        inventory:Number(value.inventory),
        allSalesVolumes:Number(value.allSalesVolumes),
    }
    // 根据类型判断，调用不同的接口
    if(type == 'add'){
        // 调用创建鲜花接口
        await flowerCreate(flowerInfo)
        ElMessage({
        type: 'success',
        message: '添加成功'
      })
    }else{
        // 调用修改鲜花接口
        await flowerModify(flowerInfo)
        ElMessage({
        type: 'success',
        message: '修改成功'
      })
    }
    // 重新获取鲜花信息
    getFlowerInfo()
    // 获取全部的数据，返回给total
    const getData = await flowerSearch()
    total.value = getData.findData.length
    loading.value = false
}
// 修改操作
const onReviseFlower = (row) =>{
    // dialogTitle.value = '修改鲜花信息'
    buttonType.value = "revise"
    flowerFormInitial.value = row
    dialogVisible.value = true
}
  // 删除操作
  const onDeleteFlower = (row) => {
    ElMessageBox.confirm(
    `确认要删除鲜花${row.name}吗`,
      '温馨提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }
    ).then(async () => {
      await flowerDelete({id:row._id})
      ElMessage({
        type: 'success',
        message: i18n.t('msg.excel.removeSuccess')
      })
      getFlowerInfo()
      // 获取全部的数据，返回给total
      const getData = await flowerSearch()
      total.value = getData.findData.length
    })
  }
    // 监听语言切换
    watchSwitchLang(getFlowerInfo)
  /**
   *  调用时机为首次挂载
   *  以及每次从缓存中被重新插入时
   * 处理导入用户后数据不重新加载的问题
   */
  onActivated(getFlowerInfo)
  onMounted(async() => {
    getFlowerInfo()
      // 获取全部的数据，返回给total
      const getData = await flowerSearch()
      total.value = getData.findData.length
  })
  </script>
  
  <style lang="scss" scoped>
  .flower-manage-container {
    .header {
      margin-bottom: 22px;
      text-align: right;
      .header-content{
        display: flex;
        justify-content: space-between;
        align-items: center;
        .search{
            display: flex;
            align-items: center;
            width: 50%;
            .input{
                width: 30%;
                margin: 0 10px;
            }
        }
      }
    }
    :deep(.el-image) {
      width: 60px;
      height: 60px;
      border-radius: 50%;
    }
  
    :deep(.el-tag) {
      margin-right: 6px;
    }
  
    .pagination {
      margin-top: 20px;
      text-align: center;
    }
  }
  </style>
  